﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace TestMain
{
    class Program
    {
        // 添加一个简单的缓存字典来替换原来的 SYSTEM_CACHE
        private static Dictionary<string, string> SYSTEM_CACHE = new Dictionary<string, string>();

        static async Task Main(string[] args)
        {
            string userid = "23844";
            string APPID = "d9ee3158-77b1-5276-a868-3e7552224cff";
            string secret = "67bcb3d8-66e7-43fc-bab2-2d0cde02f103";
            string spk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYpQ+hhHZ3BtFO82eT9ws4gIxHI25O4jUoH6SEnzNS3P/LK5KkbxgurlmlvwWqnHiMPP2e+piV+5d69MBXS5v3nzomFq1yvLaAowB3uenSHKhrDJYju44EqTc585T4mQ1GfeNbzKe0vNea6N+vH2PoHAnwK47stYZ/Xt8Bbj2NGQIDAQAB";

            SYSTEM_CACHE["SERVER_PUBLIC_KEY"] = spk;
            string spk1 = SYSTEM_CACHE.ContainsKey("SERVER_PUBLIC_KEY") ? SYSTEM_CACHE["SERVER_PUBLIC_KEY"] : "";
            // 使用RSA加密密钥
            string encryptSecret = RSAEncrypt(secret, spk1);
            Console.WriteLine($"Encrypted secret: {encryptSecret}");
            string encryptUserid = RSAEncrypt(userid, spk);
            Console.WriteLine("加密后的userid:" + encryptUserid);

            if (encryptSecret != null)
            {
                // 调用ECOLOGY系统接口进行注册
                string result = await ApplyTokenAsync("http://oa.maxwell-gp.com.cn:8090", APPID, encryptSecret);
                Console.WriteLine($"testGetoken(): {result}");

                // 解析返回的JSON数据
                try
                {
                    var datas = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
                    foreach (var item in datas)
                    {
                        Console.WriteLine($"{item.Key}: {item.Value}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"解析JSON失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 调用ECOLOGY系统接口进行注册
        /// </summary>
        static async Task<string> ApplyTokenAsync(string baseUrl, string appId, string encryptedSecret)
        {
            
            using (var client = new HttpClient())
            {
                // 创建请求内容
                var content = new StringContent("", Encoding.UTF8, "application/json");

                // 设置请求头
                client.DefaultRequestHeaders.Add("appid", appId);
                client.DefaultRequestHeaders.Add("secret", encryptedSecret);
                client.DefaultRequestHeaders.Add("time", "3600");

                try
                {
                    // 发送POST请求
                    var response = await client.PostAsync($"{baseUrl}/api/ec/dev/auth/applytoken", content);
                    response.EnsureSuccessStatusCode();

                    return await response.Content.ReadAsStringAsync();
                }
                catch (HttpRequestException ex)
                {
                    Console.WriteLine($"HTTP请求失败: {ex.Message}");
                    return $"{{ \"error\": \"HTTP请求失败: {ex.Message}\" }}";
                }
            }
        }

        /// <summary>
        /// 使用RSA公钥加密数据（支持X.509格式公钥）
        /// </summary>
        static string RSAEncrypt(string data, string publicKey)
        {
            try
            {
                // 将Base64公钥转换为字节数组
                byte[] publicKeyBytes = Convert.FromBase64String(publicKey);

                using (RSA rsa = RSA.Create())
                {
                    // 导入X.509格式的公钥
                    rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);

                    // 加密数据，使用PKCS#1填充
                    byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                    byte[] encryptedBytes = rsa.Encrypt(dataBytes, RSAEncryptionPadding.Pkcs1);

                    return Convert.ToBase64String(encryptedBytes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"RSA加密失败: {ex.Message}");
                Console.WriteLine($"StackTrace: {ex.StackTrace}");
                return null;
            }
        }
    }
}